/*
*    l3qd - Light, light, lightweight queue
*    Copyright (C) 2024  Marcus Pedersén marcus@marcux.org
*
*    This program is free software: you can redistribute it and/or modify
*    it under the terms of the GNU General Public License as published by
*    the Free Software Foundation, either version 3 of the License, or
*    (at your option) any later version.
*
*    This program is distributed in the hope that it will be useful,
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*    GNU General Public License for more details.
*
*    You should have received a copy of the GNU General Public License
*    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package cancel

import (
	"fmt"
	"github.com/spf13/cobra"
	"notabug.org/marcux/l3q/internal/client"
	"os"
	"os/user"
	"strconv"
)

var cancelJobCmdFlagVerbose bool

var cancelJobCmd = &cobra.Command{
	Use:   "job JOBID",
	Args:  cobra.ExactArgs(1),
	Short: "Cancel specified running or queued job.",
	Long: `Description:
  Cancel specified running or queued job.
  JOBID is required as a positional argument and is the id number of job to cancel.
  User can only cancel jobs that has been added by user.`,
	Run: func(cmd *cobra.Command, args []string) {
		u, err := user.Current()
		if err != nil {
			if cancelJobCmdFlagVerbose {
				fmt.Fprintf(os.Stderr, "Failed to get current user.\n%s\n", err)
			} else {
				fmt.Fprintf(os.Stderr, "Failed to get current user.\n")
			}

			os.Exit(1)
		}

		jobid, err := strconv.Atoi(args[0])

		if err != nil {
			fmt.Fprintf(os.Stderr, "Failed to parse JOBID: %s, as integer.\nJOBID is required to be a positive integer.\nTry -h or --help for help.\n",
				args[0])

			if cancelJobCmdFlagVerbose {
				fmt.Fprintf(os.Stderr, "%s\n", err)
			}

			os.Exit(1)
		}

		if jobid <= 0 {
			fmt.Fprintf(os.Stderr, "JOBID is required to be a positive integer.\nTry -h or --help for help.\n")
			os.Exit(1)
		}

		cancelJob(jobid, u.Username)
	},
}

func cancelJob(jobid int, user string) {
	urlSuffix := fmt.Sprintf("/job/cancel?id=%d&user=%s", jobid, user)

	client.UrlPatch(urlSuffix, cancelJobCmdFlagVerbose)

	fmt.Printf("Job with id: %d successfully cancelled.\n", jobid)
}

func init() {
	cancelJobCmd.Flags().BoolVarP(&cancelJobCmdFlagVerbose, "verbose", "v", false, "Print verbose output")
}
